package com.jahepi.android;

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;

public class GPS implements LocationListener {
	
	private static String TAG = "GPS";
	
	// Cada 15 minutos
	private static final int INTERVALO = 900000;
	
	private AplicacionBase app;
	private LocationManager locationManager;
	private Handler handler;
	
	private class Hilo extends Thread {
		public void run() {
			try {
				Log.d(TAG, "Hilo ejecutandose...");
				Thread.sleep(INTERVALO);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			Log.d(TAG, "Escuchando GPS...");
			handler.post(new Runnable() {
				public void run() {
					GPS.this.iniciar();
				}
			});
			Log.d(TAG, "Hilo GPS finalizado...");
		}
	};
	
	public GPS(AplicacionBase app) {
		this.app = app;
		handler = new Handler();
		locationManager = (LocationManager) this.app.getSystemService(Context.LOCATION_SERVICE);
	}
	
	public void iniciar() {
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
	}
	
	public void onLocationChanged(Location location) {
		app.setViajeGPS(location.getLatitude(), location.getLongitude());
		locationManager.removeUpdates(this);
		Hilo hilo = new Hilo();
		hilo.start();
	}

	public void onProviderDisabled(String provider) {
		
	}

	public void onProviderEnabled(String provider) {
		
	}

	public void onStatusChanged(String provider, int status, Bundle extras) {
		Log.d(TAG, provider);
	}
}
